package com.cs.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cs.constant.CategoryConstant;
import com.cs.domain.Category;
import com.cs.mapper.CategoryMapper;
import com.cs.service.CategoryService;
import com.netflix.ribbon.proxy.annotation.CacheProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
@CacheConfig(cacheNames = "com.cs.service.impl.CategoryServiceImpl") //命名的空间隔离
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{
    @Autowired
    private CategoryMapper categoryMapper;
    /**
     * 查询所有的分类
     * @return
     */
    @Cacheable(key = CategoryConstant.CATEGORY_ALL_PREFIX)
    @Override
    public List<Category> list() {
        List<Category> categories = categoryMapper.selectList(new LambdaQueryWrapper<Category>().orderByDesc(Category::getRecTime));
        return categories;
    }

    /**
     * 查询商品的父级分类
     *
     * @return
     */
    @Override
    @Cacheable(key = CategoryConstant.CATEGORY_PARENT_PREFIX)
    public List<Category> findParentCategory() {
        List<Category> categories = categoryMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, 0L).eq(Category::getStatus, 1));
        return categories;
    }

    /**
     * 添加商品的分类
     * @param category
     * @return
     */
    @Override
    @Caching(evict = {
            @CacheEvict(key=CategoryConstant.CATEGORY_ALL_PREFIX),
            @CacheEvict(key=CategoryConstant.CATEGORY_PARENT_PREFIX)
    })
    public boolean save(Category category) {
        log.info("添加商品的分类{}", JSON.toJSONString(category));
        category.setShopId(1L);
        category.setRecTime(new Date());
        category.setUpdateTime(new Date());
        Long parentId = category.getParentId();
        if(parentId==null || parentId.equals(0L)){
            parentId=0L;
            category.setGrade(1);
        }else{
            //说明是子节点
            Category category1 = categoryMapper.selectById(parentId);
            if(!ObjectUtils.isEmpty(category1)){
                category.setGrade(2);
            }
        }
        int insert = categoryMapper.insert(category);
        return insert>0;
    }
}
